package merchant.space;

import java.io.File;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

public class MyViewCollectionActivity extends Activity {
	
	private TextView name;
	private TextView cattegory;
	private TextView description;
	private GridView gridview;
	
	private MyViewCollectionActivity context;
	
	private Collection collection;
	
	private static final int LOADING = 0;
	private ProgressDialog loadingdialog = null;
	
	private ViewItemsAdapter adapter;
	private int fotocount,position;
	
	private String totalpath;
	private Navigation navigation;
	
	  public void onCreate(Bundle savedInstanceState) {
	    	
		  super.onCreate(savedInstanceState);
	      setContentView(R.layout.myviewcollection);
	     collection=DataLink.getMyCollection();
	      
	    	Log.d("n items",String.valueOf(collection.getItems().size()));
	      context=this;
	    		
	   	//  showDialog(LOADING);
	   	    
	   	  name = (TextView)findViewById(R.id.title);
		  description = (TextView)findViewById(R.id.description);
		  cattegory = (TextView)findViewById(R.id.cattegory);
		 
		  gridview = (GridView) findViewById(R.id.gridview);
		  
		  adapter=new ViewItemsAdapter(context,collection);
		  gridview.setAdapter(adapter);
		  setListViewHeightBasedOnChildren(gridview);
		  gridview.setOnItemClickListener(new OnItemClickListener() 
		    {
		        public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
		        {
		            
		        	context.position=position;
		        	showDialog(LOADING);
		    		new Thread(){ public void run() {
		    			
		    			DataLink.prepareMyItem(context.position);
		    			threadHandler.sendEmptyMessage(0);
		    			  }}.start();
		         }
		    });
		  
		 
		  fotocount=0;
		  
		  refresh();
	   	}
	    	
	    	
	 
	  
	  public void refresh()
	  {
		  
		 name.setText(collection.getName());
		 description.setText(collection.getDescription());
		 cattegory.setText(collection.getCattegory());
		 
		 adapter=new ViewItemsAdapter(context,collection);
		 gridview.setAdapter(adapter);
		 setListViewHeightBasedOnChildren(gridview);
		 
		 name.setFocusableInTouchMode(true);
	     name.requestFocus();
	   		
	
	  }
	  
	  public void viewItem()
	  {
		  Log.d("pp",getParent().toString());
		  Intent viewitem = new Intent(getParent(), MyViewItemActivity.class);
		  MyCollectionsGroupActivity parentActivity = (MyCollectionsGroupActivity) getParent();
		  parentActivity.startChildActivity("MyViewItemActivity", viewitem);
	  }
	    	
	  @Override
		protected Dialog onCreateDialog(int id) {
			switch (id) {
			case LOADING:
				loadingdialog = new ProgressDialog(getParent());
				loadingdialog.setTitle("Merchant");
				loadingdialog.setMessage("Loading data");
				return loadingdialog;
				
				
			default:
				return null;
			}
		}
	  
	  private final Handler threadHandler = new Handler() {
			@Override
			public void handleMessage(Message arg0) {
				
				switch(arg0.what)
				{
					
					case 0:
					{
						dismissDialog(LOADING);//Log.d("DIZE",String.valueOf(collection.getItems().size()));
						//refresh();
						//dismissDialog(LOADING);
						viewItem();
					} break;
					
					default:
					{
						 Log.d("aaah","FUCK");
					} break;
				}
		};		}; 		
		

		 public void setListViewHeightBasedOnChildren(GridView listView) {
		       
			
			 
			 int rows = adapter.getCount()/3; 
			
			 int rest = adapter.getCount()%3; 
			 if(rest!=0) rows++;
			 Log.d("ROWS",String.valueOf(rows));
			 
				int totalHeight = 0;
		        int columncount=0;
		        int maxheight=0;
		        
		     int verticalspace = 50;
		       listView.setVerticalSpacing(verticalspace);
		        for (int i = 0; i < adapter.getCount(); i++) {
		            
		            View listItem = adapter.getView(i, null, listView);
		            listItem.measure(0, 0);
		            Log.d("MEASSURED",String.valueOf(listItem.getMeasuredHeight()));
		            if(columncount==0)
		            	maxheight=listItem.getMeasuredHeight();
		            else
		            	if(listItem.getMeasuredHeight()>maxheight)
		            		maxheight=listItem.getMeasuredHeight();
		            
		            if(columncount==2)
		            {
		            	totalHeight+=maxheight;
		            	columncount=0;
		            }
		            else columncount++;
		        }
		        
		        
		        if (columncount!=0)
		        	totalHeight+=maxheight;
		        	
		        for(int i=0;i<rows;i++)
		        	totalHeight+=verticalspace;

		        ViewGroup.LayoutParams params = listView.getLayoutParams(); 
		        params.height = totalHeight;// + 20;// + ( (adapter.getCount() - 1));
		        listView.setLayoutParams(params);
		        listView.requestLayout();
		    }


		 
		  public boolean onCreateOptionsMenu(Menu menu) {
			  Log.d("CREATING MENU","VIEW");
			  super.onCreateOptionsMenu(menu);
			  menu.add(0,0,0,"Add Item");
			  Log.d("CREATING MENU","VIEW");
			
			  return true;
		    }
		    
		    public boolean onOptionsItemSelected(MenuItem item) {
		    	  super.onOptionsItemSelected(item);
		    	  switch (item.getItemId()) {
		    	  case 0:
		    		  
		    		  addItem();
		    		  
		    	      break;
		    	 
		    	  
		    	  default:

		    	  break;
		    	  }
		    	  return false;
		    }
		    
		    public void addItem()
		    {
		    	//	useCam();
		    	 Intent viewcoll = new Intent(getParent(), AddItemActivity.class);
	    		 MyCollectionsGroupActivity parentActivity = (MyCollectionsGroupActivity) getParent();
	    		 parentActivity.startChildActivity("AddItemActivity", viewcoll);
		    			
		   	}
		    
		 
		    
			 
			  
			public void useCam(){
				
				  Uri fileUri;
				   File file;
				// create Intent to take a picture and return control to the calling application
			      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			      
			  String name = String.valueOf(fotocount);
			      fotocount++;
			      fileUri = CamControl.getOutputMediaFileUri(CamControl.MEDIA_TYPE_IMAGE,name); // create a file to save the image
			      intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
			      intent.putExtra("myid", "cam"); // set
			      totalpath=fileUri.getPath();
			      // start the image capture Intent
			      Activity parent = getParent();
			      Log.d("p->",parent.toString());
			  getParent().startActivityForResult(intent, CamControl.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
			    
			   
			}
			
			public void afterPhoto()
			{
				
				 Log.d("AFTER","sa");
				 
				 Item newItem = new Item(this.collection.getId(),50,totalpath,String.valueOf(fotocount),true,true,"awesome","");
				 newItem.getThumb();
				 collection.addItem(newItem);
				 refresh();
				 
			}
			
			@Override
		    public void onResume() {
		    	//super.onResume();
			 super.onResume();
		    	
		    	Log.d("RESUMING","MYVIEWCOLLECTION");
		    	MyCollectionsGroupActivity parent = (MyCollectionsGroupActivity) getParent();
		    	if (parent.getNavigation().myCollectionsRefresh()==true)
		    		finish();
		    }
			

			
			
}
	    	


